package com.dingreading.cloud.web.service.impl;

import com.dingreading.cloud.web.service.CdnService;
import com.dingreading.cloud.web.util.RC4Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

@RefreshScope
@Service
public class CdnServiceImpl implements CdnService {

    @Value("${aliYun.cdn.privateKey}")
    private String cdnPrivateKey;


    @Override
    public boolean validateToken(String token, String ip, String remoteAddr, String uri, String httpReferer) throws Exception {
        // token解密
        String decryToken = RC4Util.decry_RC4(token, cdnPrivateKey);
//        System.out.println("decryToken = " + decryToken);
        if (StringUtils.isBlank(decryToken)) {
            return false;
        }
        String[] split = StringUtils.split(decryToken, "-");
        if (split.length != 3) {
            return false;
        }
        String tokenExpire = split[0];
        String tokenIp = split[1];
        String tokenFileUrl = split[2];
//        System.out.println("tokenExpire = " + tokenExpire);
//        System.out.println("tokenIp = " + tokenIp);
//        System.out.println("tokenFileUrl = " + tokenFileUrl);
        if (StringUtils.isBlank(tokenExpire) || StringUtils.isBlank(tokenIp) || StringUtils.isBlank(tokenFileUrl)) {
            return false;
        }
        // 验证ip
        if (!ip.equals(tokenIp) && !remoteAddr.equals(tokenIp)) {
            // 联通手机号码的ip会出现最后一位不同的问题：220.205.252.228、 220.205.252.164
            String ip1 = StringUtils.substringBeforeLast(remoteAddr, ".");
            String ip2 = StringUtils.substringBeforeLast(tokenIp, ".");
            if (!ip1.equals(ip2)) {
                return false;
            }
        }
        // 验证文件地址是否一致
        if (!uri.contains(tokenFileUrl)) {
            return false;
        }
        // 验证过期时间
        long timestamp = Long.parseLong(tokenExpire);
        long currentTime = System.currentTimeMillis(); // 假设timestamp是秒级
        if (timestamp < currentTime) {
            return false;
        }

        return true;
    }

}
